package com.rlz.base.util;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.BatteryManager;
import android.os.Build;
import android.os.Bundle;
import android.os.PowerManager;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;

import com.rlz.base.app.Base;

import java.lang.reflect.Method;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;

import static android.content.Context.WIFI_SERVICE;
import static android.telephony.TelephonyManager.NETWORK_TYPE_1xRTT;
import static android.telephony.TelephonyManager.NETWORK_TYPE_CDMA;
import static android.telephony.TelephonyManager.NETWORK_TYPE_EDGE;
import static android.telephony.TelephonyManager.NETWORK_TYPE_EHRPD;
import static android.telephony.TelephonyManager.NETWORK_TYPE_EVDO_0;
import static android.telephony.TelephonyManager.NETWORK_TYPE_EVDO_A;
import static android.telephony.TelephonyManager.NETWORK_TYPE_EVDO_B;
import static android.telephony.TelephonyManager.NETWORK_TYPE_GPRS;
import static android.telephony.TelephonyManager.NETWORK_TYPE_HSDPA;
import static android.telephony.TelephonyManager.NETWORK_TYPE_HSPA;
import static android.telephony.TelephonyManager.NETWORK_TYPE_HSPAP;
import static android.telephony.TelephonyManager.NETWORK_TYPE_HSUPA;
import static android.telephony.TelephonyManager.NETWORK_TYPE_IDEN;
import static android.telephony.TelephonyManager.NETWORK_TYPE_UMTS;

/**
 * Created by RLZ
 * on 2020/11/28
 */
public class DeviceUtils {

    public static String mAndroidId;
    public static final String NETWORK_TYPE_WIFI = "WIFI";
    public static final String NETWORK_TYPE_5G = "5G";
    public static final String NETWORK_TYPE_4G = "4G";
    public static final String NETWORK_TYPE_3G = "3G";
    public static final String NETWORK_TYPE_2G = "2G";
    public static final String NETWORK_NONE = "none";
    public static final String NETWORK_HAVE = "have";

    /**
     * 判断当前设备是否是PAD
     */
    public static boolean isPad() {
        return (Base.obtain().getResources().getConfiguration().screenLayout
                & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE;
    }

    /**
     * 获取meta－data数据
     */
    public static String getMetaData(Context context, String key) {
        Bundle metaData = null;
        Object value = null;
        try {
            ApplicationInfo ai = context.getPackageManager().getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
            metaData = ai.metaData;
            if (null != metaData) {
                value = metaData.get(key);
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return String.valueOf(value).trim();
    }


    /**
     * 获取 系统按本号
     *
     * @return
     */
    public static String getSdkVersion() {
        return Build.VERSION.RELEASE;
    }


    /**
     * 获取版本号
     *
     * @return 当前应用的版本号
     */
    public static int getVersionCode(Context context) {
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            return info.versionCode;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }


    /**
     * 获取设备的 当前电量
     */
    @SuppressLint("NewApi")
    public static String getPhonePower(Context context) {
        BatteryManager batteryManager = (BatteryManager) context.getSystemService(Context.BATTERY_SERVICE);
        String battery = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            battery = batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY) + "";
        }
        return battery == null ? "1" : battery;
    }


    /**
     * 判断某个界面是否在前台
     *
     * @param context   Context
     * @param className 界面的类名
     * @return 是否在前台显示
     */
    public static boolean isForeground(Context context, String className) {
        if (context == null || TextUtils.isEmpty(className))
            return false;
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(1);
        if (list != null && list.size() > 0) {
            ComponentName cpn = list.get(0).topActivity;
            return className.equals(cpn.getClassName());
        }
        return false;
    }


    /**
     * 打开系统浏览器
     */
    public static void openBrowser(Activity activity, String url) {
        Intent i = new Intent(Intent.ACTION_VIEW);
        i.setData(Uri.parse(url));
        activity.startActivity(i);
    }


    /**
     * 版本号 对比 V2
     */
    public static boolean compareVersions(Context context, String serviceVersion) {
        if (context == null || TextUtils.isEmpty(serviceVersion)) {
            return false;
        }
        String currentVersion = getVersionName(context);
        if (TextUtils.equals(currentVersion, serviceVersion)) return false;

        String[] currentArray = currentVersion.split("\\.");
        String[] serviceArray = serviceVersion.split("\\.");

        if (serviceArray.length == serviceArray.length) {
            for (int i = 0; i < serviceArray.length; i++) {
                if (Integer.parseInt(serviceArray[i]) > Integer.parseInt(currentArray[i])) {
                    return true;
                } else if (Integer.parseInt(serviceArray[i]) < Integer.parseInt(currentArray[i])) {
                    return false;
                } else if (Integer.parseInt(serviceArray[i]) == Integer.parseInt(currentArray[i])) {

                }
            }
        } else {
            if (serviceArray.length > currentArray.length) {
                for (int i = 0; i < currentArray.length; i++) {
                    if (Integer.parseInt(serviceArray[i]) > Integer.parseInt(currentArray[i])) {
                        return true;
                    } else if (Integer.parseInt(serviceArray[i]) < Integer.parseInt(currentArray[i])) {
                        return false;

                    } else if (Integer.parseInt(serviceArray[i]) == Integer.parseInt(currentArray[i])) {
                        if (currentArray.length == 1) {
                            continue;
                        }
                        if (i == currentArray.length - 1) {

                            for (int j = i; j < serviceArray.length; j++) {
                                if (Integer.parseInt(serviceArray[j]) != 0) {
                                    return true;
                                }
                                if (j == serviceArray.length - 1) {
                                    return false;
                                }
                            }
                            return true;
                        }
                    }
                }
            } else {
                for (int i = 0; i < serviceArray.length; i++) {
                    if (Integer.parseInt(serviceArray[i]) > Integer.parseInt(currentArray[i])) {
                        return true;
                    } else if (Integer.parseInt(serviceArray[i]) < Integer.parseInt(currentArray[i])) {
                        return false;

                    } else if (Integer.parseInt(serviceArray[i]) == Integer.parseInt(currentArray[i])) {
                        if (serviceArray.length == 1) {
                            continue;
                        }
                        if (i == serviceArray.length - 1) {
                            return false;

                        }
                    }
                }
            }
        }
        return false;
    }


    /**
     * 获取版本名
     *
     * @return 当前应用的版本号
     */
    public static String getVersionName(Context context) {
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            return info.versionName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }


    /**
     * 判断是否安装过支付宝
     */
    public static boolean checkAliPayInstalled(Context context) {
        try {
            Uri uri = Uri.parse("alipays://platformapi/startApp");
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            ComponentName componentName = intent.resolveActivity(context.getPackageManager());
            return componentName != null;
        } catch (Exception e) {
            return false;
        }
    }


    /**
     * 判断是否安装过微信
     */
    public static boolean checkWeChatInstalled(Context context) {
        final PackageManager packageManager = context.getPackageManager();// 获取packagemanager
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
        for (int i = 0; i < pinfo.size(); i++) {
            String pn = pinfo.get(i).packageName;
            if (pn.equals("com.tencent.mm")) {
                return true;
            }
        }
        return false;
    }


    /**
     * 判断qq是否可用
     */
    public static boolean isQQClientAvailable(Context context) {
        final PackageManager packageManager = context.getPackageManager();
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
        for (int i = 0; i < pinfo.size(); i++) {
            String pn = pinfo.get(i).packageName;
            if (pn.equals("com.tencent.mobileqq")) {
                return true;
            }
        }
        return false;
    }


    /**
     * 判断是否安装了微博
     */
    public static boolean isSinaClientAvailable(Context context) {
        final PackageManager packageManager = context.getPackageManager();
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
        for (int i = 0; i < pinfo.size(); i++) {
            String pn = pinfo.get(i).packageName;
            if (pn.equals("com.sina.weibo")) {
                return true;
            }
        }
        return false;
    }


    /**
     * 判断某个界面是否在前台
     *
     * @param activity 要判断的Activity
     * @return 是否在前台显示
     */
    public static boolean isForeground(Activity activity) {
        return isForeground(activity, activity.getClass().getName());
    }

    public static boolean isLockPower() {
        PowerManager pm = (PowerManager) Base.obtain().getSystemService(Context.POWER_SERVICE);
        return pm.isScreenOn();
    }


    public static String getAndroidId() {
        if (mAndroidId == null || mAndroidId.length() == 0) {
            mAndroidId = Settings.Secure.getString(Base.obtain().getContentResolver(), Settings.Secure.ANDROID_ID);
        }
        return mAndroidId;
    }


    /**
     * 获取设备的唯一识别号
     */
    @SuppressLint({"MissingPermission", "HardwareIds"})
    public static String getIMEIDeviceId() {
        String deviceId;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            deviceId = Settings.System.getString(Base.obtain().getContentResolver(), Settings.System.ANDROID_ID);
        } else {
            final TelephonyManager telephonyManager = (TelephonyManager) Base.obtain().getSystemService(Context.TELEPHONY_SERVICE);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (Base.obtain().checkSelfPermission(Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                    return null;
                }
            }

            if (telephonyManager.getDeviceId() != null) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    deviceId = telephonyManager.getImei();
                } else {
                    deviceId = telephonyManager.getDeviceId();
                }
            } else {
                deviceId = Settings.Secure.getString(Base.obtain().getContentResolver(), Settings.Secure.ANDROID_ID);
            }
        }

        if (TextUtils.isEmpty(deviceId)) {
            deviceId = "";
        }
        return deviceId;
    }


    /**
     * 判断是否有网络连接
     */
    public static boolean isNetworkConnected() {
        ConnectivityManager connectivityManager = (ConnectivityManager)
                Base.obtain().getSystemService(Context.CONNECTIVITY_SERVICE);
        @SuppressLint("MissingPermission") NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetInfo != null && activeNetInfo.isConnected();
    }


    /**
     * 获取当前 的网络状态
     */
    public static String getNetworkType() {
        String strNetworkType = "";
        final ConnectivityManager connectivityManager = (ConnectivityManager) Base.obtain().
                getSystemService(Context.CONNECTIVITY_SERVICE);
        //获取链接网络信息
        @SuppressLint("MissingPermission") final NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected()) {
            if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                strNetworkType = NETWORK_TYPE_WIFI;
            } else if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
                String strSubTypeName = networkInfo.getSubtypeName();

                int networkType = networkInfo.getSubtype();
                switch (networkType) {
                    case NETWORK_TYPE_GPRS:
                    case NETWORK_TYPE_EDGE:
                    case NETWORK_TYPE_CDMA:
                    case NETWORK_TYPE_1xRTT:
                    case NETWORK_TYPE_IDEN:
                        strNetworkType = NETWORK_TYPE_2G;
                        break;
                    case NETWORK_TYPE_UMTS:
                    case NETWORK_TYPE_EVDO_0:
                    case NETWORK_TYPE_EVDO_A:
                    case NETWORK_TYPE_HSDPA:
                    case NETWORK_TYPE_HSUPA:
                    case NETWORK_TYPE_HSPA:
                    case NETWORK_TYPE_EVDO_B:
                    case NETWORK_TYPE_EHRPD:
                    case NETWORK_TYPE_HSPAP:
                        strNetworkType = NETWORK_TYPE_3G;
                        break;
                    case TelephonyManager.NETWORK_TYPE_LTE:
                        strNetworkType = NETWORK_TYPE_4G;
                        break;
                    case TelephonyManager.NETWORK_TYPE_NR:
                        strNetworkType = NETWORK_TYPE_5G;
                        break;
                    default:
                        // 中国移动 联通 电信 三种3G制式
                        if (strSubTypeName.equalsIgnoreCase("TD-SCDMA") ||
                                strSubTypeName.equalsIgnoreCase("WCDMA") ||
                                strSubTypeName.equalsIgnoreCase("CDMA2000")) {
                            strNetworkType = NETWORK_TYPE_3G;
                        } else {
                            strNetworkType = strSubTypeName;
                        }
                        break;
                }
            } else {
                strNetworkType = "未知网络类型";
            }
        } else {
            strNetworkType = NETWORK_NONE;
        }
        return strNetworkType;
    }

    @SuppressLint("MissingPermission")
    public static String getIPAddress() {
        NetworkInfo info = ((ConnectivityManager) Base.obtain().getApplicationContext()
                .getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
        if (info != null && info.isConnected()) {
            if (info.getType() == ConnectivityManager.TYPE_MOBILE) {//当前使用2G/3G/4G网络
                try {
                    //Enumeration<NetworkInterface> en=NetworkInterface.getNetworkInterfaces();
                    for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                        NetworkInterface intf = en.nextElement();
                        for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                            InetAddress inetAddress = enumIpAddr.nextElement();
                            if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                                return inetAddress.getHostAddress();
                            }
                        }
                    }
                } catch (SocketException e) {
                    e.printStackTrace();
                }

            } else if (info.getType() == ConnectivityManager.TYPE_WIFI) {//当前使用无线网络
                WifiManager wifiManager = (WifiManager) Base.obtain()
                        .getApplicationContext().getSystemService(WIFI_SERVICE);
                WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                return intIP2StringIP(wifiInfo.getIpAddress());
            }
        }

        return "";
    }

    /**
     * 将得到的int类型的IP转换为String类型
     */
    public static String intIP2StringIP(int ip) {
        return (ip & 0xFF) + "." +
                ((ip >> 8) & 0xFF) + "." +
                ((ip >> 16) & 0xFF) + "." +
                (ip >> 24 & 0xFF);
    }

    /**
     * 判断是否开启了 “屏幕自动旋转”
     */
    public static boolean isScreenAutoRotate(Context context) {
        int gravity = 0;
        try {
            gravity = Settings.System.getInt(context.getContentResolver(),
                    Settings.System.ACCELEROMETER_ROTATION);
        } catch (Settings.SettingNotFoundException e) {
            e.printStackTrace();
        }

        return gravity == 1;
    }


    public static String getConnectWifiName() {
        WifiManager wifiManager = (WifiManager) Base.obtain().getApplicationContext().getSystemService(WIFI_SERVICE);
        assert wifiManager != null;
        @SuppressLint("MissingPermission") WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        if (wifiInfo == null) return "";
        return wifiInfo.getSSID();
    }


    public static String getWIFISSID() {
        String ssid = null;

        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.O || Build.VERSION.SDK_INT == Build.VERSION_CODES.P) {
            WifiManager mWifiManager = (WifiManager) Base.obtain()
                    .getApplicationContext().getSystemService(Context.WIFI_SERVICE);

            assert mWifiManager != null;
            @SuppressLint("MissingPermission") WifiInfo info = mWifiManager.getConnectionInfo();

            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
                return info.getSSID();
            } else {
                return info.getSSID().replace("\"", "");
            }
        } else if (Build.VERSION.SDK_INT == Build.VERSION_CODES.O_MR1) {
            ConnectivityManager connManager = (ConnectivityManager) Base
                    .obtain().getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
            assert connManager != null;
            @SuppressLint("MissingPermission") NetworkInfo networkInfo = connManager.getActiveNetworkInfo();
            if (networkInfo.isConnected()) {
                if (networkInfo.getExtraInfo() != null) {
                    return networkInfo.getExtraInfo().replace("\"", "");
                }
            }
        }
        return ssid;
    }


    /**
     * 从第一个非本地主机接口获取IP地址
     */
    public static String getIPAddress(boolean useIPv4) {
        try {
            List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface intf : interfaces) {
                List<InetAddress> addrs = Collections.list(intf.getInetAddresses());
                for (InetAddress addr : addrs) {
                    if (!addr.isLoopbackAddress()) {
                        String sAddr = addr.getHostAddress().toUpperCase();
                        boolean isIPv4 = addr instanceof Inet4Address;
                        if (useIPv4) {
                            if (isIPv4)
                                return sAddr;
                        } else {
                            if (!isIPv4) {
                                int delim = sAddr.indexOf('%'); // drop ip6 port suffix
                                return delim < 0 ? sAddr : sAddr.substring(0, delim);
                            }
                        }
                    }
                }
            }
        } catch (Exception ignored) {
        } // for now eat exceptions
        return "";
    }

    /**
     * 解析路径URL，从文件名获取数据库ID。
     */
    public static String parseResourceId(String path) {
        String result = null;
        if (path != null && path.length() > 0) {
            int index = path.lastIndexOf("/");
            //File name like "id".mp3
            String fileName = path.substring(index + 1);
            result = fileName.substring(0, fileName.lastIndexOf("."));
        }

        return result;
    }


    /**
     * 获取手机型号
     *
     * @return 手机型号
     */
    public static String getPhoneModel() {
        return Build.MODEL;
    }


    /**
     * 获取手机厂商
     * HuaWei
     */
    public static String getPhoneBrand() {
        return Build.BRAND;
    }


    /**
     * 获取当前手机设备名
     * 设备统一型号,不是"关于手机"的中设备名
     */
    public static String getDeviceName() {
        return Build.DEVICE;
    }

    /**
     * 获取手机厂商加型号 作为手机名称
     */
    public static String getPhoneModelBrand() {
        return getPhoneBrand() + " " + getPhoneModel();
    }

    /**
     * 获取当前手机系统版本号
     */
    public static String getVersionRelease() {
        return Build.VERSION.RELEASE;
    }


    /**
     * HUAWEI HWELE ELE-AL00 10
     */
    public static String getPhoneDetail() {
        return getPhoneBrand() + " " + getDeviceName() + " " +
                getPhoneModel() + " " + getVersionRelease();
    }

    /**
     * 获取网络运营商名称
     * <p>中国移动、如中国联通、中国电信</p>
     *
     * @return 运营商名称
     */
    public static String getNetworkOperatorName() {
        String opeType = "unknown";
        // No sim
        if (!hasSim(Base.obtain().getApplicationContext())) {
            return opeType;
        }

        TelephonyManager tm = (TelephonyManager) Base.obtain().getApplicationContext().getSystemService(Context.TELEPHONY_SERVICE);
        String operator = tm.getSimOperator();
        if ("46001".equals(operator) || "46006".equals(operator) || "46009".equals(operator)) {
            opeType = "中国联通";
        } else if ("46000".equals(operator) || "46002".equals(operator) || "46004".equals(operator) || "46007".equals(operator)) {
            opeType = "中国移动";

        } else if ("46003".equals(operator) || "46005".equals(operator) || "46011".equals(operator)) {
            opeType = "中国电信";
        } else {
            opeType = "unknown";
        }
        return opeType;
    }

    /**
     * 检查手机是否有sim卡
     */
    private static boolean hasSim(Context context) {
        TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        String operator = tm.getSimOperator();
        if (TextUtils.isEmpty(operator)) {
            return false;
        }
        return true;
    }

    /**
     * 判断数据流量开关是否打开
     */
    public static boolean isMobileDataEnabled(Context context) {
        try {
            Method method = ConnectivityManager.class.getDeclaredMethod("getMobileDataEnabled");
            method.setAccessible(true);
            ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            return (Boolean) method.invoke(connectivityManager);
        } catch (Throwable t) {
            return false;
        }
    }


    public static boolean checkDeviceHasNavigationBar(Context context) {
        boolean hasNavigationBar = false;
        Resources rs = context.getResources();
        int id = rs.getIdentifier("config_showNavigationBar", "bool", "android");
        if (id > 0) {
            hasNavigationBar = rs.getBoolean(id);
        }
        try {
            Class systemPropertiesClass = Class.forName("android.os.SystemProperties");
            Method m = systemPropertiesClass.getMethod("get", String.class);
            String navBarOverride = (String) m.invoke(systemPropertiesClass, "qemu.hw.mainkeys");
            if ("1".equals(navBarOverride)) {
                hasNavigationBar = false;
            } else if ("0".equals(navBarOverride)) {
                hasNavigationBar = true;
            }
        } catch (Exception ignored) {
        }
        return hasNavigationBar;
    }
}
